#include "StdAfx.h"
#include "CudaHostBuffer.h"
#include "CudaDeviceBuffer.h"
using namespace System;

namespace GRIP
{
	namespace Cuda
	{
		InternalCudaHostBuffer::InternalCudaHostBuffer(int size)
		{
			CudaErrorCheck(cudaMallocHost((void**) &buffer, size));
		}
		
		InternalCudaHostBuffer::~InternalCudaHostBuffer()
		{
			CudaErrorCheck(cudaFreeHost(buffer));
		}

		CudaHostBuffer::CudaHostBuffer(int width, int height, int elementSize)
		{
			Width = width;
			Height = height;
			Size = width * height * elementSize;
			InternalBuffer = new InternalCudaHostBuffer(Size);
			ManagedBufferPtr = IntPtr(InternalBuffer->buffer);
		}

		BYTE* CudaHostBuffer::Ptr()
		{
			return InternalBuffer->buffer;
		}

		IntPtr CudaHostBuffer::Data()
		{
			return ManagedBufferPtr;
		}
		
		void CudaHostBuffer::CopyToDevice(CudaDeviceBuffer^ Target)
		{
			CudaErrorCheck(cudaMemcpy(
				Target->Ptr(),
				InternalBuffer->buffer,
				Size,
				cudaMemcpyHostToDevice));
		}
		
		void CudaHostBuffer::CopyFromDevice(CudaDeviceBuffer^ Source)
		{
			CudaErrorCheck(cudaMemcpy(
				InternalBuffer->buffer,
				Source->Ptr(),
				Size,
				cudaMemcpyDeviceToHost));
		}

		int CudaHostBuffer::BufferSize()
		{
			return Size;
		}

		int CudaHostBuffer::GetWidth()
		{
			return Width;
		}

		int CudaHostBuffer::GetHeight()
		{
			return Height;
		}
	}
}
